package org.cu.ooad.finalproject.layar;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

public class FileIO extends IOAdapter {
	
	private final static Logger log = Logger.getLogger(FileIO.class.getName());

	private String filename;
	private List<POI> POIs;

	public FileIO(String filename) {
		this.filename = filename;
		try {
			POIs = loadPOIs();
			if (POIs==null) POIs = new ArrayList<POI>();
		} catch (Exception e) {
			log.severe("Error while loading POIs: "+e.getMessage());
			POIs = new ArrayList<POI>();
		}
	}

	private List<POI> loadPOIs() throws NumberFormatException, IOException {

		List<POI> POIs = new ArrayList<POI>();
		
		// open static web file
		FileInputStream fiStream = new FileInputStream(filename);
		DataInputStream dStream = new DataInputStream(fiStream);
		BufferedReader br = new BufferedReader(new InputStreamReader(dStream));

		double lat_coord = 0, lon_coord = 0;
		String strLine;
		POI tempPOI;

		// Read File Line By Line
		while ((strLine = br.readLine()) != null) {
			// Print the content on the console
			String[] strArray;
			strArray = strLine.split(",");
			lat_coord = Double.valueOf(strArray[1]);
			lon_coord = Double.valueOf(strArray[2]);

			tempPOI = new POI(
					strArray[0].substring(1, strArray[0].length() - 1),
					lat_coord, lon_coord);

			POIs.add(tempPOI);
		}

		dStream.close();

		return POIs;
	
	}

	@Override
	public List<POI> getAllPOIs() {
		return POIs;
	}

	@Override
	public void insertPOI(POI poi) {}

	@Override
	public void updatePOITitle(POI poi) {}

	@Override
	public void updatePOILocation(POI poi) {}

	@Override
	public void deletePOI(POI poi) {}

	@Override
	public POI getPOIByTitle(String title) {
		for (int i=0; i<POIs.size(); i++) {
			if (POIs.get(i).getTitle().equals(title)) {
				return POIs.get(i);
			}
		}
		return null;
	}

	@Override
	public POI getPOIByLocation(double lat, double lon) {
		POI tempPOI = null;
		for (int i=0; i<POIs.size(); i++) {
			tempPOI = POIs.get(i);
			if (tempPOI.getLat()==lat && tempPOI.getLon()==lon) {
				return tempPOI;
			}
		}
		return null;
	}

}
